/*
 * This file is part of the Android Dimensions Editor Project: http://code.google.com/p/android-dimension-editor/
 *  
 * Copyright (c) 2013 Rick Falck
 *  
 * This code is licensed under the terms of the Apache License Version 2.0.
 * You may use this code according to the license.
 *
 * The terms of the license can be found in the root directory of this project's repository as well as at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under these Licenses is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See each License for the specific language governing permissions and
 * limitations under that License.
 */
package model;
/**
 * <b>public class ItemValue extends ItemTextField</b>
 * <p>
 * This class encapsulates one dimens value
 * 
 * @author Rick Falck
 */
public class ItemValue extends ItemTextField {
	private final boolean mCanEdit;

	public ItemValue(String value, boolean canEdit) {
		super(value);
		mCanEdit = canEdit;
		setAlignment(javafx.geometry.Pos.CENTER);
		if (!canEdit) {
			this.setEditable(false);
		}
	}

	@Override
	protected String getMyStyle() {
		return "itemvalue";
	}

	public boolean editValue() {
		if (!mCanEdit) {
			return true;
		}
		String value = getText().trim();
		
		return isDimensionValue(value);
	}

	public static boolean isDimensionValue(String value) {
		// edit/get the units of measure
		DIMENSION_TYPE typeUsed = null;
		for (DIMENSION_TYPE dv : DIMENSION_TYPE.values()) {
			if (value.endsWith(dv.name())) {
				typeUsed = dv;
				break;
			}
		}

		// Not a valid unit
		if (typeUsed == null) {
			return false;
		}

		// Check the numeric part
		try {
			String num = value.substring(0, value.length() - typeUsed.name().length());
			Integer.parseInt(num);
		} catch (Exception e) { // IndexOutOfBoundsException or
								// NumberFormatException
			return false;
		}

		return true;
	}

	public enum DIMENSION_TYPE {
		dip, dp, in, pt, px, mm, sp;
	}
}
